//
//  ReadViewController.m
//  Leisure
//
//  Created by 大展 on 16/4/18.
//  Copyright © 2016年 张展. All rights reserved.
//

#import "ReadViewController.h"
@interface ReadViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, strong)NSMutableArray *dataSource; // 存放数据的数组
@property (nonatomic, strong)UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *scrArray;
@property (nonatomic, strong) CycleScrollView *cycleScrollView;

@end

@implementation ReadViewController

- (UICollectionView *)collectionView {

    if (!_collectionView) {

        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];

        layout.itemSize = CGSizeMake(100, 100);
        layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, kHeight/3+64, kWidth, kHeight*2/3) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}

- (NSMutableArray *)dataSource {

    if (!_dataSource) {

        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

//创建轮播图
- (void)creatCycleScrollView {
    NSLog(@"轮播图！！！");
    _cycleScrollView = [[CycleScrollView alloc] initWithFrame:CGRectMake(0, 64, kWidth, kHeight/3) animationDuration:5];

    NSMutableArray *viewsArray = [@[] mutableCopy];
    for (int i = 0; i < self.scrArray.count; ++i) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:_cycleScrollView.bounds];
        NSString *imgUrl = self.scrArray[i][@"img"];
        [imageView sd_setImageWithURL:[NSURL URLWithString:imgUrl]];
        [viewsArray addObject:imageView];
    }
    [self.view addSubview:_cycleScrollView];

    _cycleScrollView.fetchContentViewAtIndex = ^UIView *(NSInteger pageIndex){
        return viewsArray[pageIndex];
    };

    _cycleScrollView.totalPagesCount = viewsArray.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return self.dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    ReadListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"read_cell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor redColor];

    [cell setCellWithReadmodel:self.dataSource[indexPath.row]];

    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(nonnull NSIndexPath *)indexPath {


    // 单例来获取抽屉的主视图
    DrawViewController *drawVC = [DrawViewController sharedManager];

    // 初始化详情页面
    ReadDetailViewController *readDetailVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"ReadDetailViewController"];
    ReadModel *model = self.dataSource[indexPath.row];
    readDetailVC.typeID = model.type;

    // push推出详情页面
    [drawVC.mainViewController.navigationController pushViewController:readDetailVC animated:YES];
    



}

- (NSMutableArray *)scrArray {

    if (!_scrArray) {

        _scrArray = [NSMutableArray array];
    }
    return _scrArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    //注册Xib
    [self.collectionView registerNib:[UINib nibWithNibName:@"ReadListCell" bundle:nil] forCellWithReuseIdentifier:@"read_cell"];
    [self fetchDataSoucreWithUrl:kReadUrl];
}



// 请求数据
- (void)fetchDataSoucreWithUrl:(NSString *)url {


    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [manager POST:url parameters:@{} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];

            NSArray *listArray = dic[@"data"][@"list"];
            for (NSDictionary *object in listArray) {

                ReadModel *model = [[ReadModel alloc]init];
                [model setValuesForKeysWithDictionary:object];
                [self.dataSource addObject:model];
            }
            [self.scrArray addObjectsFromArray:dic[@"data"][@"carousel"]];

            dispatch_async(dispatch_get_main_queue(), ^{

                [self.collectionView reloadData];
                [self creatCycleScrollView];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            });


        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {


        }];
    });

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
